import { QueryClient, useMutation } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import { AxiosError } from "axios";
import { LessonService } from "@/shared/api/api.lesson";

export function useCreateLesson(themeId:number) {
    const { register, handleSubmit } = useForm<{
        tittle: string
        award: number
    }>();
    const queryClient = new QueryClient

    const createLessonMutation = useMutation(
        {
            mutationFn: LessonService.create,
            onError: (error: (AxiosError<{ message: string }>)) => error,
        }, queryClient
    );
    const errorMessage = createLessonMutation.error ? createLessonMutation.error.response?.data.message : undefined;

    return {
        register,
        errorMessage,
        isSucces: createLessonMutation.isSuccess,
        handleSubmit: handleSubmit((data) => createLessonMutation.mutate(
            {
                ...data,
                award: Number(data.award),
                themeId:themeId
            })),
    };
}